'use strict';
const BaseService = require('./base');
const rp = require('request-promise');
const StringUtil = require('../utils/StringUtil');
const HelperUtil = require('../utils/HelperUtil');
const Constant = require('../config/Constant');
const OperatorType = require('../config/OperatorType');
const ResponseUtil = require('../utils/ResponseUtil');
const RCEM = require('../utils/ResultCodeEnumMsg');


class ProductService extends BaseService {


    async selectPureByPrimaryKey(id) {
        let sql = 'select * from t_product where id = ?';
        let result = await this.executeSqlFirst(sql, [id]);
        return result;
    }


    async getProductList() {
        let loginUserInfo = this.ctx.getLoginInfo();
        let operatorType = loginUserInfo.operatorType;
        let operatorId = loginUserInfo.operatorId;
        let createBy = loginUserInfo.createBy;
        let {pageNum, pageSize} = this.ctx.query;

        let sql = 'select SQL_CALC_FOUND_ROWS * from t_product where del_flag=0 and status = 1 order by create_time desc  ';

        sql = this.addMysqlPageSize(sql, pageNum, pageSize);

        let result = await this.queryPageData(sql, []);

        return result;
    }

    generateMonthlySchedule(data, deductionDateType, deductionDateValue) {
        const result = [];
        const today = new Date();

        for (let i = 0; i < data.length; i++) {
            let date = new Date(today);

            if (deductionDateType === '10') {
                // 下单顺延
                date.setMonth(date.getMonth() + i); // 每期加 i 个月
                date.setDate(date.getDate() + deductionDateValue); // 顺延天数
            } else if (deductionDateType === '20') {
                // 每月固定日，从下个月开始
                date.setMonth(date.getMonth() + 1 + i); // 从下个月开始，每期加 i 个月
                date.setDate(deductionDateValue); // 固定日
                // 处理月份天数不足的情况
                while (date.getMonth() !== (today.getMonth() + 1 + i) % 12) {
                    date.setDate(date.getDate() - 1);
                }
            } else {
                throw new Error('未知 deductionDateType');
            }

            result.push({
                price: data[i].toFixed(2),
                date: date.toISOString().split('T')[0],
            });
        }

        return result;
    }

    async getProductDetail() {
        let productId = this.ctx.params.productId;
        if (!productId) {
            return null;
        }
        let product =  await this.selectPureByPrimaryKey(productId);

        let installmentArr = product.installmentArr;
        try{
            installmentArr = JSON.parse(installmentArr);
            let arr = [];
            installmentArr.map(function (item) {
                arr.push({
                    name:item+'期',
                    value:item
                })
            });
            product.installmentCovertArr = arr;
        }catch (e) {
            product.installmentCovertArr = [];
        }
        try{
            let installmentPriceCoverMap = {};
            let installmentPriceArr = JSON.parse(product.installmentPriceArr);
           /* for (let key in installmentPriceArr) {
                let data = installmentPriceArr[key];
                let newData = this.generateMonthlySchedule(data, product.deductionDateType, product.deductionDateValue);
                installmentPriceCoverMap[key] = newData;
            }*/
            product.installmentPriceCoverMap = installmentPriceArr;
        }catch (e) {
            product.installmentPriceCoverMap = {};
        }
        return product;
    }

    async applyProduct() {
        let loginUserInfo = this.ctx.getLoginInfo();
        let operatorType = loginUserInfo.operatorType;
        let operatorId = loginUserInfo.operatorId;
        let createBy = loginUserInfo.createBy;
        let {id, productName, price, trainingPeriod, teachingMethod, installment, installmentPrice,} = this.ctx.request.body;
        if (!id || !productName || !price || !trainingPeriod || !teachingMethod || !installment || !installmentPrice) {
            return ResponseUtil.resError('参数错误');
        }
        if(!HelperUtil.isNumberWithTwoDecimals(price)){
            return ResponseUtil.resError('价格请输入数字');
        }

        const product = await this.selectPureByPrimaryKey(id);
        if(!product){
            return ResponseUtil.resError('未找到该产品');
        }
        if(product.status != 1){
            return ResponseUtil.resError('该产品已下架');
        }




        let params = {
            id:StringUtil.getUUIDV2(),
            user_id:operatorId,
            product_id:id,
            tenant_id:product['tenantId'],
            product_no:product['productNo'],
            product_name:productName,
            price:price,
            training_period:trainingPeriod,
            teaching_method:teachingMethod,
            installment:installment,
            installment_price:JSON.stringify(installmentPrice)
        };

        return await this.executeInsert('t_product_apply',params);
    }


}

module.exports = ProductService;
